package code.LinkList;

import struct.LinkList;
import struct.ListNode;

public class ReverseList {
	public static void main(String[] args) {
		var listNode = LinkList.generateLinkList(new int[]{1, 2, 3, 4, 5, 6});
		LinkList.printLinkList(listNode);

		ReverseList reverseList = new ReverseList();
		//递归翻转并打印结果
		ListNode listNode1 = reverseList.reverseRecu(listNode);
		LinkList.printLinkList(listNode1);
		//迭代翻转并打印结果
		ListNode listNode2 = reverseList.reverseIteration(listNode1);
		LinkList.printLinkList(listNode2);
	}

	//迭代实现单链表翻转
	public ListNode reverseIteration(ListNode head) {
		ListNode cur = head;
		ListNode pre = null;
		while (cur != null) {
			ListNode next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		return pre;
	}

	//迭代实现单链表翻转
	public ListNode reverseRecu(ListNode head) {
		if (head == null || head.next == null) {
			return head;
		}
		ListNode node = reverseRecu(head.next);
		head.next.next = head;
		head.next = null;
		return node;
	}
}
